package com.huaqin.obeacons;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.huaqin.obeacons.bluetooth.BluetoothUtils;
import com.huaqin.obeacons.bluetooth.IBeacon;
import com.huaqin.obeacons.utils.MyDatabaseUtil;
import com.huaqin.obeacons.utils.ShakeListener;
import com.huaqin.obeacons.utils.ShakeListener.OnShakeListener;
import com.huaqin.obeacons.utils.SharedPreferenceUtil;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class HomeFragment extends Fragment {
	private ImageView rssiBarView;
	private int signal_oldLevel = 0;
	private int colorbar_Level = 0;
	private int[] signal_range_min = new int[] { -113, -79, -64, -59, -34 };
	private int[] signal_range_max = new int[] { -75, -60, -45, -30, 0 };
	private static final int[] rssiBarImages = {
			R.drawable.device_rssi_color_00, R.drawable.device_rssi_color_01,
			R.drawable.device_rssi_color_02, R.drawable.device_rssi_color_03,
			R.drawable.device_rssi_color_04 };

	private TextView dateTextView;
	private TextView timerTextView;
	private Handler mHandler;

	private ArrayList<IBeacon> mLeDevices = null;
	private Context mContext;
	private String TAG = "HomeFragment";
	private TextView deviceUuidView;
	private TextView deviceNameView;
	private TextView clockTipsView;
	private IBeaconReceiver receiver;
	private long oldReceiveDataTime = 0;

	private ImageButton clickBtn;
	private ShakeListener mShakeListener;
	private IBeacon ibeacon = null;
	private long oldClickDataTime = 0;
	private long oldShakeDataTime = 0;
	private Toast toast;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home, null);

		rssiBarView = (ImageView) view.findViewById(R.id.device_rssi_bar);
		timerTextView = (TextView) view.findViewById(R.id.device_time);
		dateTextView = (TextView) view.findViewById(R.id.device_date);
		deviceNameView = (TextView) view.findViewById(R.id.device_name);
		deviceUuidView = (TextView) view.findViewById(R.id.device_id);
		clockTipsView = (TextView) view.findViewById(R.id.clock_tips_text);

		clickBtn = (ImageButton) view.findViewById(R.id.click_btn);
		clickBtn.setEnabled(false);

		long currentTime = System.currentTimeMillis();
		Log.d(TAG, "currentTime：" + currentTime);
		SimpleDateFormat dateformatter = new SimpleDateFormat(
				"yyyy年MM月dd日     EE");
		SimpleDateFormat timeformatter = new SimpleDateFormat("HH:mm:ss");
		Date date = new Date(currentTime);
		dateTextView.setText(dateformatter.format(date));
		timerTextView.setText(timeformatter.format(date));
		
		String usr_name = SharedPreferenceUtil.getName(mContext);
		String usr_number = SharedPreferenceUtil.getAccount(mContext);
		if (usr_name != null) {
			((TextView) view.findViewById(R.id.usr_name)).setText(usr_name);
		}
		if (usr_number != null) {
			((TextView) view.findViewById(R.id.usr_number)).setText(usr_number);
		}
		toast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);

		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = getActivity().getApplicationContext();

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				Log.e(TAG, "handleMessage");
				super.handleMessage(msg);
			}
		};
		mHandler.postDelayed(updateTimeRun, 1000);
		if (android.os.Build.VERSION.SDK_INT < 18) {
			Log.e(TAG, "Not supported prior to API 18.");
		} else {
			BluetoothUtils.initBluetooth(mContext);
			mContext.startService(new Intent(
					"com.huaqin.obeacons.bluetooth.DEVICE_SCAN_SERVICE"));
		}
		// 注册广播接收器
		IBeaconReceiver receiver = new IBeaconReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.huaqin.obeacons.updateIBeaconData");
		mContext.registerReceiver(receiver, filter);
		// 摇一摇，打个卡
		mShakeListener = new ShakeListener(mContext);
		mShakeListener.setValidShakingCount(2);
		mShakeListener.setOnShakeListener(new OnShakeListener() {
			@Override
			public void onShake() {
				// TODO Auto-generated method stub
				if (ibeacon != null) {
					if (SystemClock.elapsedRealtime() - oldShakeDataTime < 5 * 1000) {
						toast.setText("亲，别摇了，您已经打过卡啦");
						oldShakeDataTime = SystemClock.elapsedRealtime();
					} else if (SystemClock.elapsedRealtime() - oldShakeDataTime < 30 * 1000) {
						toast.setText("亲，您已经打过卡了，过会儿再来玩吧");
						oldShakeDataTime = SystemClock.elapsedRealtime();
					} else if (ibeacon.getRssi() < -70) {
						toast.setText("打卡失败，距离考勤机太远，请靠近信号区再操作！");
					} else {
						MyDatabaseUtil.insertDateTimeHelpExtra(mContext,
								new Date());
						oldShakeDataTime = SystemClock.elapsedRealtime();
						hadnleRemindEvent();
						toast.setText("打卡成功，未知的总是美好的，新的一天，加油吧！");
					}
				} else {
					toast.setText("打卡失败，没有搜索到考勤机信息，请靠近信号区再操作！");
				}
				toast.show();
			}
		});

	}

	public class IBeaconReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e(TAG, "IBeaconReceiver");
			Bundle bundle = intent.getExtras();
			ibeacon = (IBeacon) bundle.getSerializable("obeacons");
			oldReceiveDataTime = SystemClock.elapsedRealtime();
//			Log.i(TAG, "ibeacon getMajor: " + ibeacon.getMajor() + " getMinor:"
//					+ ibeacon.getMinor() + " rssi:" + ibeacon.getRssi()
//					+ " getProximityUuid:" + ibeacon.getProximityUuid());
			if(ibeacon != null){
				updateRssiBarStrength(ibeacon.getRssi());
	
				String uuid = ibeacon.getProximityUuid();
				deviceUuidView.setText(uuid);
				deviceNameView.setText(BluetoothUtils.getDeviceName(uuid));
				clockTipsView.setText(R.string.clock_tips_text);
			}
			clickBtn.setEnabled(true);
			clickBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (ibeacon != null) {
						if (SystemClock.elapsedRealtime() - oldClickDataTime < 5 * 1000) {
							toast.setText("亲，别点了，您已经打过卡啦");
							oldClickDataTime = SystemClock.elapsedRealtime();
						} else if (SystemClock.elapsedRealtime()
								- oldClickDataTime < 30 * 1000) {
							toast.setText("亲，您已经打过卡了，过会儿再来玩吧");
							oldClickDataTime = SystemClock.elapsedRealtime();
						} else if (ibeacon.getRssi() < -70) {
							toast.setText("打卡失败，距离考勤机太远，请靠近信号区再操作！");
						} else {
							MyDatabaseUtil.insertDateTimeHelpExtra(mContext,
									new Date());
							oldClickDataTime = SystemClock.elapsedRealtime();
							hadnleRemindEvent();
							toast.setText("打卡成功，未知的总是美好的，新的一天，加油吧！");
						}
					} else {
						toast.setText("打卡失败，没有搜索到考勤机信息，请靠近信号区再操作！");
					}
					toast.show();
				}
			});
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 启动监听器
		mShakeListener.startListening();

	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 关闭监听器
		mShakeListener.stopListening();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private final Runnable updateTimeRun = new Runnable() {
		public void run() {
			/*
			 * long time = System.currentTimeMillis(); final Calendar mCalendar
			 * = Calendar.getInstance(); mCalendar.setTimeInMillis(time); mHours
			 * = mCalendar.get(Calendar.HOUR); mMinutes =
			 * mCalendar.get(Calendar.MINUTE); mSenconds =
			 * mCalendar.get(Calendar.SECOND);
			 * timerTextView.setText(mHours+":"+mMinutes+":"+mSenconds);
			 */
			long currentTime = System.currentTimeMillis();
			Log.d(TAG, "currentTime：" + currentTime);
			SimpleDateFormat dateformatter = new SimpleDateFormat(
					"yyyy年MM月dd日     EE");
			SimpleDateFormat timeformatter = new SimpleDateFormat("HH:mm:ss");
			Date date = new Date(currentTime);
			dateTextView.setText(dateformatter.format(date));
			timerTextView.setText(timeformatter.format(date));
			if (oldReceiveDataTime != 0
					&& SystemClock.elapsedRealtime() - oldReceiveDataTime > 2 * 1000) {
				updateRssiBarStrength(-100);
				clickBtn.setEnabled(false);
				deviceNameView.setText("x号楼考勤机");
				deviceUuidView.setText("xxxx-xxxx-xxxx-xxxx-xxxx");
				clockTipsView.setText(R.string.clock_no_signal);
				ibeacon = null;
			}
			mHandler.postDelayed(updateTimeRun, 1000);
		}

	};

	private void hadnleRemindEvent() {
		// TODO Auto-generated method stub
		if (SharedPreferenceUtil.getAppVoiceEnable(mContext)) {
			Uri notification = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			Ringtone ring = RingtoneManager.getRingtone(mContext, notification);
			ring.setStreamType(AudioManager.STREAM_SYSTEM);
			ring.play();
		}
		if (SharedPreferenceUtil.getAppVibrateEnable(mContext)) {
			Vibrator vibrator = (Vibrator) mContext
					.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(300);
		}
	};

	private void updateRssiBarStrength(int rssi) {
		/*
		 * if (rssi >= 0 || rssi <= -80) { colorbar_Level = 0; } else { if (rssi
		 * < signal_range_min[signal_oldLevel]) { if (signal_oldLevel > 0) {
		 * signal_oldLevel--; } } else if (rssi >
		 * signal_range_max[signal_oldLevel]) { if (signal_oldLevel < 4) {
		 * signal_oldLevel++; } } colorbar_Level = signal_oldLevel;
		 * signal_oldLevel = colorbar_Level; }
		 */
		if (rssi >= 0 || rssi <= -80) {
			colorbar_Level = 0;
		} else if (rssi <= -65) {
			colorbar_Level = 1;
		} else if (rssi <= -50) {
			colorbar_Level = 2;
		} else if (rssi <= -35) {
			colorbar_Level = 3;
		} else if (rssi < 0) {
			colorbar_Level = 4;
		}
		rssiBarView.setBackgroundResource(rssiBarImages[colorbar_Level]);
		if (colorbar_Level == 2 || colorbar_Level == 3 || colorbar_Level == 4) {
			// hadnleRemindEvent();
		}
	}

}